<?php

defined('_SECURITY_TOKEN') or die("caia fora");

class modelview extends model
{
	
	function __construct(  )
	{
		
		
		
	}
	
	
	public function getViewMetaDataFromKey( $table_name, $notation ){
				
		$result=false;
				
		try{	
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			//$id	=	$parameters->id;
			
			if( !empty($table_name)){
				
				//if($this->exists_table($table_name)){
					
					$result	=	$this->getViewDataFromKeyPeriodo($table_name);
					
					//var_dump( $data );
					
					$file_notation = PATH_DOWNLOAD._SEPARATOR_SO
									.$table_name."_metadata.".$notation;
					
					
					
					switch($result[0]->id_time_update_data){
						
						case '1':
							//tempo real
								
							$query = sprintf("SELECT metadata
											WHERE table_name='%s%s'",
												configuration::table_prefix,	
												configuration::table_view, 
												$table_name);
														
							$result = $db->getQuery($query);
							
							if($result){
						
								//atualiza informação de atualizacao de dado
								$data = $this->setViewDataFromKeyPeriodoUpdate(
											$table_name);
								
								$data = json_decode($result[0]->metadata);
								
								$result=array();
								
								foreach( $data as $key=>$item ){
									
									
									foreach( $item as $key2=>$item2){
										
										$add_item[$key2]=$item2;
									}
									
									array_push($result, (object) $add_item );
								}
								
								
									
								switch( $notation ){
									case 'csv':
										
										$result = application::arrayToCsv($result);
										break;
									case 'json':
										
										$result = application::arrayToJson($result);
										break;
								}
								
								//var_dump( $result );
								//exit();
										
												
							}else{
								$result="";	
							}		
	
	
							if(file_exists($file_notation))
								unlink($file_notation);
							
								
							$out = fopen($file_notation, 'w');
							fwrite($out, $result);
							fclose($out);
							
									
							break;
						case '2':
							//uma vez por dia
	
							if( $result[0]->last_update_data=="" || 
										$result[0]->last_update_data>0){
								
								$query = sprintf("SELECT metadata FROM \"%s%s\"
											WHERE table_name='%s'",
											configuration::table_prefix,	
													configuration::table_view, 
													$table_name);
													
								
								$result = $db->getQuery($query);
								
								//var_dump($result);
								//
								if($result){
								
									//atualiza informação de atualizacao de dado
									$data = $this->setViewDataFromKeyPeriodoUpdate(
											$table_name);
									
									
									$data = json_decode($result[0]->metadata);
									
									$result=array();
									
									foreach( $data as $key=>$item ){
										
										
										foreach( $item as $key2=>$item2){
											
											$add_item[$key2]=$item2;
										}
										
										array_push($result, (object) $add_item );
									}
								
									switch( $notation ){
										case 'csv':
											
											$result = application::arrayToCsv(
																		$result);
											break;
										case 'json':
											
											$result = application::arrayToJson(
																		$result);
											break;
									}
									
									if(file_exists($file_notation))
										unlink($file_notation);
									
									
									$out = fopen($file_notation, 'w');
									fwrite($out, $result);
									fclose($out);
					
								}
								
								
							}else{
								//busca arquivo em cache
								
								//PATH_DOWNLOAD
								$result=false;
								//pegar o arquivo local
								
								$file = PATH_DOWNLOAD._SEPARATOR_SO
											.$table_name.".".$notation;
								
								if(file_exists($file_notation)){
									
									//arquivo já existe
									
								}else{
									
									
									$query = sprintf("SELECT metadata FROM \"%s%s\"
													WHERE table_name='%s'",	
													configuration::table_prefix,
														configuration::table_view, 
														$table_name);
													
									$result = $db->getQuery($query);
									
									//var_dump($result);
									//
									if($result){
									
										//atualiza informação de atualizacao de dado
										$data = $this->setViewDataFromKeyPeriodoUpdate(
													$table_name);
											
										
										$data = json_decode($result[0]->metadata);
										
										$result=array();
										
										foreach( $data as $key=>$item ){
											
											
											foreach( $item as $key2=>$item2){
												
												$add_item[$key2]=$item2;
											}
											
											array_push($result, (object) $add_item );
										}
								
									
										switch( $notation ){
											case 'csv':
												
												$result = application::arrayToCsv(
																		$result);
												break;
											case 'json':
												
												$result = application::arrayToJson(
																		$result);
												break;
										}
									
									}else{
											$result="";
									}
										
										//if(file_exists($file_notation))
											//unlink($file_notation);
										
									$out = fopen($file_notation, 'w');
									fwrite($out, $result);
									fclose($out);
									
									
								}
								
							}
			
							break;
						case '3':
							//uma vez por semana
							
							
							if( $result[0]->last_update_data=="" || 
										$result[0]->last_update_data>6){
								
								$query = sprintf("SELECT * FROM \"%s\"", 
																$table_name);
																
								$result = $db->getQuery($query);
								
								//var_dump($result);
								//
								if( $result){
								
									//atualiza informação de atualizacao de dado
									$data = $this->setViewDataFromKeyPeriodoUpdate(
											$table_name);
									
									
									switch( $notation ){
										case 'csv':
											
											$result = application::arrayToCsv(
																		$result);
											break;
										case 'json':
											
											$result = application::arrayToJson(
																		$result);
											break;
									}
								}else{
									
									$result="";
								}	
								
								
								if(file_exists($file_notation))
									unlink($file_notation);
								
								
								$out = fopen($file_notation, 'w');
								fwrite($out, $result);
								fclose($out);
					
								
								
							}else{
								//busca arquivo em cache
								
								//PATH_DOWNLOAD
								$result=false;
								//pegar o arquivo local
								
								$file = PATH_DOWNLOAD._SEPARATOR_SO
											.$table_name.".".$notation;
								
								if(file_exists($file_notation)){
									
									//arquivo já existe
									
								}else{
									
									
									$query = sprintf("SELECT * FROM \"%s\"", 
																	$table_name);
									$result = $db->getQuery($query);
									
									//var_dump($result);
									//
									if( $result){
									
										//atualiza informação de atualizacao de dado
									$data = $this->setViewDataFromKeyPeriodoUpdate(
												$table_name);
										
										
										switch( $notation ){
											case 'csv':
												
												$result = application::arrayToCsv(
																		$result);
												break;
											case 'json':
												
												$result = application::arrayToJson(
																		$result);
												break;
										}
								
									}else{
										$result="";
									}		
									
										//if(file_exists($file_notation))
											//unlink($file_notation);
										
										$out = fopen($file_notation, 'w');
										fwrite($out, $result);
										fclose($out);						
	
								}
								
							}
	
	
							
							
							break;
						default:
							
							break;
					}
	
					$result = $file_notation;
					
					
				//}else{
				//	$result=false;//array( (object) array("status"=>"not key exist") );
				//}
				
			}
			//$query = sprintf("SELECT  * FROM %s WHERE user_id=%d;",
	        //         	configuration::table_view, application::getUser_id());

		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
				
				
		return $result;
		
	}
	
	
	
	
	public function getViewDataFromKey( $table_name, $notation ){
				
		$result=false;
			
		try{
						
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			//$id	=	$parameters->id;
			
			if( !empty($table_name)){
				
				if($this->exists_table($table_name)){
					
					$result	=	$this->getViewDataFromKeyPeriodo($table_name);
					
					//var_dump( $data );
					
					$file_notation = PATH_DOWNLOAD._SEPARATOR_SO
									.$table_name.".".$notation;
					
					
					
					switch($result[0]->id_time_update_data){
						
						case '1':
							//tempo real
								
							$query = sprintf("SELECT * FROM \"%s\"", $table_name);
							$result = $db->getQuery($query);
							
							if($result){
						
								//atualiza informação de atualizacao de dado
								$data = $this->setViewDataFromKeyPeriodoUpdate(
											$table_name);
											
								switch( $notation ){
									case 'csv':
										
										$result = application::arrayToCsv($result);
										break;
									case 'json':
										
										$result = application::arrayToJson($result);
										break;
								}
								
												
							}else{
								$result="";	
							}		
	
	
							if(file_exists($file_notation))
								unlink($file_notation);
							
								
							$out = fopen($file_notation, 'w');
							fwrite($out, $result);
							fclose($out);
							
									
							break;
						case '2':
							//uma vez por dia
	
							if( $result[0]->last_update_data=="" || 
										$result[0]->last_update_data>0){
								
								$query = sprintf("SELECT * FROM \"%s\"", 
																	$table_name);
								$result = $db->getQuery($query);
								
								//var_dump($result);
								//
								if( count($result)){
								
									//atualiza informação de atualizacao de dado
									$data = $this->setViewDataFromKeyPeriodoUpdate(
											$table_name);
									
									
									switch( $notation ){
										case 'csv':
											
											$result = application::arrayToCsv(
																		$result);
											break;
										case 'json':
											
											$result = application::arrayToJson(
																		$result);
											break;
									}
									
									if(file_exists($file_notation))
										unlink($file_notation);
									
									
									$out = fopen($file_notation, 'w');
									fwrite($out, $result);
									fclose($out);
					
								}
								
								
							}else{
								//busca arquivo em cache
								
								//PATH_DOWNLOAD
								$result=false;
								//pegar o arquivo local
								
								//$file = PATH_DOWNLOAD._SEPARATOR_SO
								//			.$table_name.".".$notation;
								
								if(file_exists($file_notation)){
									
									//arquivo já existe
									
								}else{
									
									
									$query = sprintf("SELECT * FROM \"%s\"", 
																	$table_name);
									$result = $db->getQuery($query);
									
									//var_dump($result);
									//
									if($result){
									
										//atualiza informação de atualizacao de dado
									$data = $this->setViewDataFromKeyPeriodoUpdate(
												$table_name);
										
										
										switch( $notation ){
											case 'csv':
												
												$result = application::arrayToCsv(
																		$result);
												break;
											case 'json':
												
												$result = application::arrayToJson(
																		$result);
												break;
										}
									
									}else{
											$result="";
									}
										
										//if(file_exists($file_notation))
											//unlink($file_notation);
										
									$out = fopen($file_notation, 'w');
									fwrite($out, $result);
									fclose($out);
									
									
								}
								
							}
			
							break;
						case '3':
							//uma vez por semana
							
							
							if( $result[0]->last_update_data=="" || 
										$result[0]->last_update_data>6){
								
								$query = sprintf("SELECT * FROM \"%s\"", 
																$table_name);
								$result = $db->getQuery($query);
								
								//var_dump($result);
								//
								if( $result){
								
									//atualiza informação de atualizacao de dado
									$data = $this->setViewDataFromKeyPeriodoUpdate(
											$table_name);
									
									
									switch( $notation ){
										case 'csv':
											
											$result = application::arrayToCsv(
																		$result);
											break;
										case 'json':
											
											$result = application::arrayToJson(
																		$result);
											break;
									}
								}else{
									
									$result="";
								}	
								
								
								if(file_exists($file_notation))
									unlink($file_notation);
								
								
								$out = fopen($file_notation, 'w');
								fwrite($out, $result);
								fclose($out);
					
								
								
							}else{
								//busca arquivo em cache
								
								//PATH_DOWNLOAD
								$result=false;
								//pegar o arquivo local
								
								//$file = PATH_DOWNLOAD._SEPARATOR_SO
								//			.$table_name.".".$notation;
								
								if(file_exists($file_notation)){
									
									//arquivo já existe
									
								}else{
									
									
									$query = sprintf("SELECT * FROM \"%s\"", 
																	$table_name);
																	
									$result = $db->getQuery($query);
									
									//var_dump($result);
									//
									if( $result){
									
										//atualiza informação de atualizacao de dado
									$data = $this->setViewDataFromKeyPeriodoUpdate(
												$table_name);
										
										
										switch( $notation ){
											case 'csv':
												
												$result = application::arrayToCsv(
																		$result);
												break;
											case 'json':
												
												$result = application::arrayToJson(
																		$result);
												break;
										}
								
									}else{
										$result="";
									}		
									
										//if(file_exists($file_notation))
											//unlink($file_notation);
										
										$out = fopen($file_notation, 'w');
										fwrite($out, $result);
										fclose($out);						
	
								}
								
							}
	
	
							
							
							break;
						case '4':
							//não atualiza
							
							
							//PATH_DOWNLOAD
							$result=false;
							//pegar o arquivo local
							
							//$file = PATH_DOWNLOAD._SEPARATOR_SO
							//			.$table_name.".".$notation;
							
							if(file_exists($file_notation)){
								
								//arquivo já existe
								
							}else{
								
								
								$query = sprintf("SELECT * FROM \"%s\"", 
																$table_name);
								$result = $db->getQuery($query);
								
								//var_dump($result);
								//
								if( $result){
								
									//atualiza informação de atualizacao de dado
								$data = $this->setViewDataFromKeyPeriodoUpdate(
											$table_name);
									
									
									switch( $notation ){
										case 'csv':
											
											$result = application::arrayToCsv(
																	$result);
											break;
										case 'json':
											
											$result = application::arrayToJson(
																	$result);
											break;
									}
							
								}else{
									$result="";
								}		
								
									//if(file_exists($file_notation))
										//unlink($file_notation);
									
								$out = fopen($file_notation, 'w');
								fwrite($out, $result);
								fclose($out);						

							}

							
							break;
						default:
							
							throw new AppException( MSG_30_TIPO_DE_ATUALIZACAO_NAO_COMPATIVEL );
							
							break;
					}
	
					$result = $file_notation;
					
					
				}else{
					$result=false;//array( (object) array("status"=>"not key exist") );
				}
				
			}
			//$query = sprintf("SELECT  * FROM %s WHERE user_id=%d;",
	        //         	configuration::table_view, application::getUser_id());
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;
		
	}
	
	
						
						
	public function setViewDataFromKeyPeriodoUpdate( $table_name ){
				
		$result=false;
			
		try{
					
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			if( !empty($table_name)){
				
				$query = sprintf("UPDATE \"%s%s\" 
									SET last_update_data=statement_timestamp() 	
								WHERE table_name='%s'",
								configuration::table_prefix,
		                 		configuration::table_view, 
		                 		$table_name);
				
				try{
					$result = $db->setQuery($query);
					
				}catch (AppException $e) {
			    	$result=false;
			    }
								
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;
		
	}
	
	
						
	public function getViewDataFromKeyPeriodo( $table_name ){
				
		$result=false;
			
		try{
				 		
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			if( !empty($table_name)){
				
				$query = sprintf("SELECT id_time_update_data, 
									DATE_PART('day', 
									 current_timestamp - last_update_data)  
									 last_update_data
									FROM \"%s%s\" 
									WHERE table_name='%s' LIMIT 1 OFFSET 0;",
								configuration::table_prefix,	
	                 			configuration::table_view, 
	                 			$table_name);
				
				$result = $db->getQuery($query);
				
				if( count($result) ){
					
					//var_dump($result);exit();
				}
								
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		//$query = sprintf("SELECT  * FROM %s WHERE user_id=%d;",
        //         	configuration::table_view, application::getUser_id());

		//$result = $db->getQuery($query);

		return $result;
		
	}
	
	
	
	public function getViewData( $user_id, $parameters ){
				
		$result=false;
		
		try{
				
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			$id	=	$parameters->id;
			
			if( !empty($id)){
				$query = sprintf("SELECT * FROM \"%s\"", md5($id));
				
				$result = $db->getQuery($query);

			}
			//$query = sprintf("SELECT  * FROM %s WHERE user_id=%d;",
	        //         	configuration::table_view, application::getUser_id());
	
			

		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;
		
	}
	
	

	
	public function getList( $user_id, $id, $column, $order, 
												$limit=10, $offset=0 ){
				
		$result=false;
		
		try{
				 		
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			$pagination = sprintf(" LIMIT %u ",$limit);	
			$pagination = $pagination.sprintf(" OFFSET %u ",$offset);
			
			
			$query = sprintf("SELECT  id,
										name_view,
										db_query,
										date_create	,
										table_name	,
										id_time_update_data,
										last_update_data 
						FROM \"%s%s\" WHERE user_id=%d 
						ORDER BY %s %s
						%s;",
						configuration::table_prefix,		
	                 	configuration::table_view, 
	                 	application::getUser_id(),
						$column,
						$order,
						$pagination);
					

			
			//$query = sprintf("SELECT  * FROM %s WHERE user_id=%d;",
	        //         	configuration::table_view, application::getUser_id());
	
			$result = $db->getQuery($query);

		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		return $result;
		
	}
	


	public function getColumnsTable( $user_id, $table_name ){
				
		$result=false;
		
		try{
					
						
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			if( !empty($table_name)){
			
				if($this->exists_table($table_name)){
					
					if($this->table_is_user($table_name, $user_id)){
						
		
	                 	$query = sprintf("SELECT column_name
											FROM information_schema.columns
											WHERE table_schema = '%s' 
											AND table_name   = '%s';",
											configuration::table_schema,
	                 						$table_name);
	
						//exit("bruno ".$query);
						$result = $db->getQuery($query);
						$result2=array();
						
						foreach( $result as $key=>$item ){
							
							array_push($result2, (object) 
											array("column"=>$item->column_name));
						}
	
						$result=$result2;
					
					}
					
				
				}			
				
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		//$query = sprintf("SELECT  * FROM %s WHERE user_id=%d;",
        //         	configuration::table_view, application::getUser_id());

		

		return $result;
		
	}
	
	

/*
	public function getViewTransformationRule( $user_id, $id ){
				
		$result=false;
		
		try{
				 		
			$db = application::getDb( configuration::db_type );
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			if( !empty($id)){
						
				$query = sprintf("SELECT json_rule FROM \"%s%s\" 
								WHERE user_id=%u and view_id=%u;",
						configuration::table_prefix,			
	                 	configuration::table_transformation, 
	                 	application::getUser_id(), 
	                 	$id);
						
				$result = $db->getQuery($query);
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		

		return $result;
		
	}*/
	
	
	public function getViewMetadata( $user_id, $id ){
				
		$result=false;
		
		try{
				 		
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			if( !empty($id)){
						
				$query = sprintf("SELECT id,metadata FROM \"%s%s\" 
								WHERE user_id=%u and id=%u;",
						configuration::table_prefix,
	                 	configuration::table_view, 
	                 	application::getUser_id(), 
	                 	$id);
						
				$result = $db->getQuery($query);
			}
		
		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		//$query = sprintf("SELECT  * FROM %s WHERE user_id=%d;",
        //         	configuration::table_view, application::getUser_id());

		

		return $result;
		
	}
	
	
	public function getItem( $user_id, $id ){
				
		$result=false;
		
		try{
					
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
			
			if( empty($id)){
				$query = sprintf("SELECT * FROM \"%s%s\" WHERE user_id=%d;",
						configuration::table_prefix,
	                 	configuration::table_view, 
	                 	application::getUser_id());
			}else{			
				$query = sprintf("SELECT * FROM \"%s%s\" WHERE user_id=%d and id=%d;",
						configuration::table_prefix,
	                 	configuration::table_view, 
	                 	application::getUser_id(), 
	                 	$id);
			}
			
			//$query = sprintf("SELECT  * FROM %s WHERE user_id=%d;",
	        //         	configuration::table_view, application::getUser_id());
	
			$result = $db->getQuery($query);

		}
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
		
		
		return $result;
		
	}
	
	
	public function viewClone( $user_id, $parameters ){
				
		$result=false;
		
		try {
					
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			$id	=	$parameters->id;
			
			if( !empty($id)){
				
			
				$query = sprintf("SELECT  	name_view, 
										  detail,
										  user_id ,
										  db_hostip, 
										  db_password ,
										  db_user,
										  db_type ,
										  db_name ,
										  db_port,
										  db_query ,
										  id_time_update_data
	  						 FROM \"%s%s\" WHERE user_id=%d and id=%d;",
	  					configuration::table_prefix,
	                 	configuration::table_view, 
	                 	application::getUser_id(), 
	                 	$id);
						
				$result = $db->getQuery($query);		
				
				$query = sprintf("INSERT INTO \"%s%s\" (
										name_view, 
										  detail,
										  user_id ,
										  db_hostip, 
										  db_password ,
										  db_user,
										  db_type ,
										  db_name ,
										  db_port,
										  db_query ,
										  id_time_update_data)
							VALUES
										('%s',
										'%s',
										%u,
										'%s',
										'%s',
										'%s',
										'%s',
										'%s',
										%u,
										'%s',
										%u)",
								configuration::table_prefix,		
			                 	configuration::table_view, 
			                 	$result[0]->name_view,
			                 	$result[0]->detail, 
			                 	application::getUser_id(), 
			                 	$result[0]->db_hostip,
			                 	$result[0]->db_password,
			                 	$result[0]->db_user,
			                 	$result[0]->db_type,
			                 	$result[0]->db_name,
			                 	$result[0]->db_port,
								$result[0]->db_query,
								$result[0]->id_time_update_data);
				
				try{
					$result = $db->setQuery($query);
					
				}catch (AppException $e) {
			    	$result=false;//throw new AppException( $e->getMessage() );
			    }
						
				
			}
		
		
		}catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }

		return $result;
		
	}
	
	
	
	
	public function table_is_user( $table_name, $user_id ){
				
		$result=false;
				
		try {
        						
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			
			$query = sprintf("select count(*) as exists 
								from \"%s%s\" 
								WHERE user_id=%u and table_name='%s'",
								configuration::table_prefix,
								configuration::table_view,
                 			 	$user_id,
                 			 	$table_name	);
					
			//var_dump( $query);	
							
			//print( $query );
			$result = $db->getQuery($query);
			
			//var_dump( $result);
			
			if( $result[0]->exists){
				
				$result=TRUE;
			}else{
				$result=FALSE;
			}
			
			//$result=true;
			
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;
		
	}
	
	
	
	
	public function exists_table( $table_name ){
				
		$result=false;
				
		try {
        						
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			
			$query = sprintf("select count(*) as exists 
								from \"pg_stat_user_tables\" 
								WHERE relname='%s';",
                 			 	$table_name);
					
			//var_dump( $query);	
							
			//print( $query );
			$result = $db->getQuery($query);
			
			//var_dump( $result);
			
			if( $result[0]->exists){
				
				$result=TRUE;
			}else{
				$result=FALSE;
			}
			
			//$result=true;
			
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;
		
	}
	
	public function drop_table( $table_name ){
				
		$result=false;
				
		try {
        						
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			
			$query = sprintf("DROP TABLE \"%s\"", $table_name);
		
			try{
				
				$result = $db->setQuery($query);
			}
		    catch (AppException $e) {
		    	$result=false;
		    }
			
			
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;
		
	}
	
	
	public function delete_view( $user_id, $parameters ){
				
		$result=false;
				
		try {
        						
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			//$parameters->db_query = urldecode($parameters->db_query);
			
			
			if(!empty($parameters->id)){

				$query = sprintf("DELETE FROM  \"%s%s\" 
								WHERE id=%u and user_id=%u",
								configuration::table_prefix,
			                 	configuration::table_view, 
								$parameters->id,
								$user_id);
					
				try{
					
					$result = $db->setQuery($query);
				
				
					if( $this->exists_table(md5($parameters->id))){
						$this->drop_table(md5($parameters->id));
					}
					
				}catch (AppException $e) {
			    	$result=false;
			    }	
		
			}

			
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;
		
	}
	
	
	
	public function save_transformation( $parameters ){
				
		$result=false;
				
		try {
        						
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			$parameters->json_rule = urldecode($parameters->json_rule);
			
			
			if(empty($parameters->id)){
				
				$query = sprintf("INSERT INTO \"%s%s\" (user_id, 
														json_rule,
														execute_order,
														view_id,
														named,
														detail
														) 
								VALUES (%u,'%s',%u,%u,'%s','%s');",
									configuration::table_prefix,
				                 	configuration::table_transformation, 
				                 	application::getUser_id(),
				                 	$parameters->json_rule,
				                 	$parameters->execute_order,
				                 	$parameters->view_id,
				                 	$parameters->named,
				    				$parameters->detail);
				
			}else{
				
				$query = sprintf("UPDATE \"%s%s\"  SET											
										json_rule='%s',
										execute_order=%u,											
										date_modified=statement_timestamp(),
										named='%s',
										detail='%s'
												
								WHERE id=%u and user_id=%u and view_id=%u",
									configuration::table_prefix,
									configuration::table_transformation, 						
									$parameters->json_rule,
									$parameters->execute_order,	
									$parameters->named,
									$parameters->detail,
									$parameters->id,  
									application::getUser_id(),               	
									$parameters->view_id);

			}
			
		
			try{
				$result = $db->setQuery($query);
			}
			catch (AppException $e) {
		    	$result=false;
		    }


	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;

	}
	
	
	
	
	
	public function save_view( $parameters ){
				
		$result=false;
				
		try {
        						
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);
	
			$parameters->db_query = urldecode($parameters->db_query);
			
			
			if(empty($parameters->id)){
				
				$query = sprintf("INSERT INTO \"%s%s\" (name_view,detail,
					user_id,db_hostip,
					db_port, db_user,db_password, db_name, db_type,db_query,
					id_time_update_data) 
					values ('%s','%s',%u,'%s',%u,'%s','%s','%s','%s','%s',%u);",
						configuration::table_prefix,
	                 	configuration::table_view, 
	                 	$parameters->name_view,
	                 	$parameters->detail,
	                 	application::getUser_id(),
	                 	$parameters->db_hostip,
	                 	$parameters->db_port,
	                 	$parameters->db_user,
	                 	$parameters->db_password,
	                 	$parameters->db_name,
	                 	$parameters->db_type,
						$parameters->db_query,
						$parameters->id_time_update_data);
				
			}else{
				
				$query = sprintf("UPDATE \"%s%s\"  SET name_view='%s',
											detail='%s',
											db_hostip='%s',
											db_port=%u, 
											db_user='%s',
											db_password='%s', 
											db_name='%s', 
											db_type='%s',
											db_query='%s',
											id_time_update_data=%u, 
											date_modified=statement_timestamp() 
												
					WHERE id=%u and user_id=%u",
						configuration::table_prefix,
	                 	configuration::table_view, 
	                 	$parameters->name_view,
	                 	$parameters->detail,	                 	
	                 	$parameters->db_hostip,
	                 	$parameters->db_port,
	                 	$parameters->db_user,
	                 	$parameters->db_password,
	                 	$parameters->db_name,
	                 	$parameters->db_type,
	                 	$parameters->db_query,
	                 	$parameters->id_time_update_data,
						$parameters->id,
						application::getUser_id());
			}
			
		
			try{
				$result = $db->setQuery($query);
			}
			catch (AppException $e) {
		    	$result=false;
		    }
			
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;
		
	}
	
	
	
	public function save_view_metadata( $parameters ){
				
		$result=false;
				
		try {
        
			$db = application::getDb( configuration::db_type);
	// 		
			$db->setParameters(configuration::db_server, 
								configuration::db_port, 
								configuration::db_username, 
								configuration::db_password,
								configuration::db_name);

			$query = sprintf("UPDATE \"%s%s\"  SET metadata='%s'
							WHERE id=%u and user_id=%u",
							configuration::table_prefix,
		                 	configuration::table_view, 
		                 	urldecode($parameters->metadata),
							$parameters->id,
							application::getUser_id());
					
			try{
				$result = $db->setQuery($query);
			}
			catch (AppException $e) {
		    	$result=false;
		    }
			
	    }
	    catch (AppException $e) {
	    	throw new AppException( $e->getMessage() );
	    }
	
		return $result;
		
	}
	
}